import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Window;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

import javax.swing.ImageIcon;
import sun.audio.*;

public class MainMenu extends Core implements KeyListener{
	
	private HashMap soundsMap;
	private ArrayList playingClips;
	
	public static void main(String[] args){
		new MainMenu().run();
	}
	
	//call init and gameloop
	public void run(){
		try{
			playingClips = new ArrayList();
			init();
			loadSounds();
			gameLoop();
		}finally{
			s.restoreScreen();
		}
	}
	
	public void loadSounds(){
		soundsMap = new HashMap();
		AudioClip clip = Applet.newAudioClip(getClass().getResource("sounds/background.wav"));
		if (clip == null){
			System.out.println("Problem loading sound");
		}else{
			soundsMap.put("background.wav", clip);
		}
	}
	
	//plays the music
	private void playMusic(boolean toLoop){
		String chosenFile = "background.wav";
		AudioClip audioClip = (AudioClip) soundsMap.get(chosenFile);
		if (audioClip == null){
			System.out.println("could not play file");
			return;
		}
		
		if(toLoop)
			audioClip.loop();
		else
			audioClip.play();
		
		playingClips.add(audioClip);
	}
	
	private void stopMusic(){
		if(!playingClips.isEmpty()){
			AudioClip audioClip;
			for(int i=0; i < playingClips.size(); i++){
				audioClip = (AudioClip) playingClips.get(i);
				audioClip.stop();
			}
			playingClips.clear();
		}
	}
	
	public void stop(){
		super.stop();
		stopMusic();
		
	}
	
	public void init(){
		super.init();
		Window w = s.getFullScreenWindow();
		w.setFocusTraversalKeysEnabled(false);
		w.addKeyListener(this);
		
	}
	public void draw(Graphics2D g) {
		Window w = s.getFullScreenWindow();
		g.setColor(w.getBackground());
		g.fillRect(0, 0, s.getWidth(), s.getHeight());
		g.setColor(w.getForeground());
		String location = currDirectory() + "images\\MainMenu.jpg";
		Image img = new ImageIcon(location).getImage();
		g.drawImage(img, 0, 0, null);
	}
	
	
	
	public void keyPressed(KeyEvent e) {
		int keyCode = e.getKeyCode();
		if (keyCode == KeyEvent.VK_ESCAPE) {
			stop();
		}else if (keyCode == KeyEvent.VK_ENTER){
			playMusic(true);
		}
		e.consume();
	}

	public void keyReleased(KeyEvent e) {
		e.consume();
		
	}


	public void keyTyped(KeyEvent e) {
		e.consume();
		
	}

}
